package com.itmsoft.util;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.itmsoft.model.HasId;

// TODO If you're going to use this methods (which is recommended) - you will
// need to write unit tests for them. Otherwise delete this unused
// class/methods.
/**
 * Usefull methods for {@link HasId} class implementations.
 */
public class InterfaceUtils
{
    /**
     * Private constructor to prevent util class instantiation.
     */
    private InterfaceUtils()
    {
    }

    /**
     * Returns id of the HasId objects collection.
     * 
     * @param objectList
     *            HasId objects collection.
     */
    public static <I extends HasId> Set<Long> getIdSet(Collection<I> objectList)
    {
        Set<Long> result = new HashSet<Long>(objectList.size());
        for (I i : objectList)
        {
            if (i.getId() != null)
            {
                result.add(i.getId());
            }
        }
        return result;
    }

    /**
     * Just a shortcut for the code: <br/>
     * <br/>
     * <code>
     * Entity entity = new Entity();<br/>
     * entity.setId(id);
     * </code> <br/>
     * <br/>
     * Usefull method to create entity with specified id. May be
     * used
     * when need
     * to delete entity having only id. No need to get it from db. Hibernate
     * manages object only by id...
     * 
     * @param id
     *            id of the object.
     * @param clazz
     *            entity class.
     * @return class with id specified populated.
     */
    public static <I extends HasId> I getReferenceWithId(Long id, Class<I> clazz)
    {
        I result;
        try
        {
            result = clazz.newInstance();
        }
        catch (Exception e)
        {
            // should never happen
            throw new IllegalArgumentException("Can't instantiate object instance.", e);
        }
        result.setId(id);
        return result;
    }

    /**
     * Searches collection of objects by id and returns found.
     * 
     * @param objects
     *            collection of HasId objects.
     * @param id
     *            object identified.
     * @return found object, null if id is null or if not found.
     */
    public static <I extends HasId> I getById(Collection<I> objects, Long id)
    {
        if (id == null)
        {
            return null;
        }
        for (I i : objects)
        {
            if (id.equals(i.getId()))
            {
                return i;
            }
        }
        return null;
    }
}
